import React, { useState } from 'react'
import { Button, Table, Image, Popconfirm, Space } from 'antd'
import { useHistory } from 'react-router-dom'
import { useMount } from 'ahooks'
import { getBannerList, bannerDelete } from './../../api/banner'
function BannerList() {
  const history = useHistory()

  const [bannerList, setBannerList] = useState([])

  useMount(() => {
    getBannerList().then(res => {
      // console.log(res)
      setBannerList(res.data.data)
    })
  })
  const columns = [
    {
      title: '序号',
      render: (text, record, index) => { // text代表当前字段，record代表整条数据，index索引值
        return <span>{ index + 1 }</span>
      }
    },
    {
      title: '提示',
      dataIndex: 'alt' // dataIndex 代表当前列与数据中的 哪个字段是匹配
    },
    {
      title: '链接',
      dataIndex: 'link'
    },
    {
      title: '图片',
      dataIndex: 'img',
      render: (text) => {
        return <Image src={text} style={{ height: 100 }}/>
      }
    },
    {
      title: '操作',
      render: (text, record, index) => {
        return (
          <Popconfirm
            title="确定删除吗?"
            onConfirm={ () => {
              bannerDelete({ bannerid: record.bannerid }).then(() => {
                // 删除完毕重新渲染数据
                getBannerList().then(res => {
                  setBannerList(res.data.data)
                })
              })
            }}
            onCancel={() => {}}
            okText="确定"
            cancelText="取消"
          >
            <Button type="danger">删除</Button>
          </Popconfirm>
        )
        
      }
    }
  ]
  return (
    <Space direction="vertical" style= {{ width: '100%' }}>
      <Button type="primary" onClick = { () => {
        history.push('/banner/add')
      }}>添加轮播图</Button>
      <Table dataSource = {bannerList} columns = {columns} rowKey="bannerid"/>
    </Space>
  )
}

export default BannerList
